<template>
  <div class="pagebox">
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['生产管理']" currentMenu="生产批次"></crumbs>
    <a-card :bordered="false" style="height: 100%; margin-top: 12px">
      <a-button @click="handleShowFilter" icon="filter"
        >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
      >
      <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
      <div class="right-btn">
        <!-- <a-button @click="importFile">导入</a-button> -->
        <PubImport @updateParentData="handleSearch" ref="PubImport" tableCode='MESS_PRODUCT_BATCH' modelName='生产批次导入模板' style='margin-right:10px;' />
        <PubExport
          :exportUrl="exportUrl"
          :columns="columns"
          :propForm="filterForm"
          :selectedRows="chooseArr"
          :sortForm="sortForm"
          :fullName="fullName"
        />
      </div>
      <a-table
        row-key="id"
        :key="tableKey"
        size="middle"
        :scroll="{ x: scrollX, y: 'calc(100vh - 366px)' }"
        :hideDefaultSelections="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
        :columns="columns"
        :dataSource="modelList"
        :pagination="false"
        @change="tableChange"
        class="j-table-force-nowrap"
        :components="drag(columns, 'PRODUCTION_BATCH_LIST')"
      >
        <span slot="actions" slot-scope="text, record">
          <a @click="qrCode(record)">打印</a>
          <span v-if="record.type == 'add' && !record.realProductionNum">
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多<a-icon type="down" /> </a>
              <a-menu slot="overlay">
                <a-menu-item @click="handleEdit(record)">
                  <a-button type="link">编辑</a-button>
                </a-menu-item>
                <a-menu-item @click="handleDelete(record)">
                  <a-button type="link">删除</a-button>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </span>
        <!-- 行信息 -->
        <div
          slot="orderCode"
          @click="orderDetail(record)"
          slot-scope="text, record"
          class="btn-text ant-table-row-cell-ellipsis"
          :title="text"
        >
          {{ text }}
        </div>
        <div
          slot="batchCode"
          @click="batchDetail(record)"
          slot-scope="text, record"
          class="btn-text ant-table-row-cell-ellipsis"
          :title="text"
        >
          {{ text }}
        </div>
        <!-- 输入框搜索 -->
        <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
          <a-input
            placeholder="请输入"
            v-model="filterForm[column.dataIndex]"
            style="width: 188px; display: block"
            @pressEnter="handleSearch"
          />
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <!-- 选择搜索 -->
        <div slot="selectDropdown" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
          <a-select
            mode="multiple"
            allowClear
            placeholder="请选择"
            :filter-option="filterOption"
            style="width: 200px"
            v-model="filterForm[column.selectKey]"
            @change="(v) => changeSelect(v, column.selectKey)"
          >
            <a-select-option v-for="(item, i) in getList(column.list)" :key="i" :value="item[column.selectValue]" :title="item[column.selectText]">{{
              item[column.selectText]
            }}</a-select-option>
          </a-select>
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <!-- 日期搜索 -->
        <div slot="datePicker" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
          <a-range-picker
            style="width: 188px"
            v-model="dateForm[column.dataIndex]"
            format="YYYY-MM-DD"
            :placeholder="['开始时间', '结束时间']"
            @change="(v) => onOk(v, column.dataIndex)"
          />
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <a-icon
          slot="searchIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
      </a-table>
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
    </a-card>
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
          <span v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </span>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="工单编号">
                <a-input v-model="filterForm.orderCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="批次编号">
                <a-input v-model="filterForm.batchCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="产品编号">
                <a-input v-model="filterForm.goodsCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="产品名称">
                <a-input v-model="filterForm.goodsName" placeholder="请输入" :maxLength="30" />
              </a-form-model-item>
              <a-form-model-item label="规格">
                <a-input v-model="filterForm.goodsSpec" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="类型">
                <a-select
                  mode="multiple"
                  :filter-option="filterOption"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['type']"
                  @change="(v) => changeSelect(v, 'type')"
                >
                  <a-select-option v-for="(item, i) in typeList" :key="i" :value="item.value" :title="item.text">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="产量">
                <a-select
                  mode="multiple"
                  :filter-option="filterOption"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['productNum']"
                  @change="(v) => changeSelect(v, 'productNum')"
                >
                  <a-select-option v-for="(item, i) in productNumList" :key="i" :value="item.value" :title="item.text">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="当前工序">
                <a-select
                  mode="multiple"
                  :filter-option="filterOption"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['currentProcessId']"
                  @change="(v) => changeSelect(v, 'currentProcessId')"
                >
                  <a-select-option v-for="(item, i) in currentProcessList" :key="i" :value="item.id" :title="item.processName">{{
                    item.processName
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="初始工序">
                <a-select
                  mode="multiple"
                  :filter-option="filterOption"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['originProcessId']"
                  @change="(v) => changeSelect(v, 'originProcessId')"
                >
                  <a-select-option v-for="(item, i) in processList" :key="i" :value="item.id" :title="item.processName">{{
                    item.processName
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="打印状态">
                <a-select
                  mode="multiple"
                  :filter-option="filterOption"
                  allowClear
                  placeholder="请选择"
                  style="width: 100%"
                  v-model="filterForm['printStatus']"
                  @change="(v) => changeSelect(v, 'printStatus')"
                >
                  <a-select-option v-for="(item, i) in statusList" :key="i" :value="item.value" :title="item.text">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="最后更新时间">
                <a-range-picker
                  style="width: 100%"
                  v-model="dateForm['lastUpdateTime']"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="(v) => onOk(v, 'lastUpdateTime')"
                />
              </a-form-model-item>
              <a-form-model-item label="创建时间">
                <a-range-picker
                  style="width: 100%"
                  v-model="dateForm['createTime']"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="(v) => onOk(v, 'createTime')"
                />
              </a-form-model-item>
              
              
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 全选/分页 -->
    <div class="uni-card resetPadding" :style="{position: 'fixed', bottom:0,right:0,zIndex:2,left:collapsed?'79px':'208px', background: '#fff',paddingLeft:'43px'} ">
      <div style="display: inline-block">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span class="btn-text" style="margin-left: 24px" @click="qrCode(false)">打印</span>
        <span class="btn-text" style="margin: 0 24px" @click="batchAction">删除</span>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span class="btn-text" @click="clearArr" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <add-modal ref="addModal" @refresh="requestData" />
    <a-modal
      v-if="printvisible"
      :width="currentEnvironment == 'dingding' ? 800 : 500"
      :visible="printvisible"
      :closable="false"
      :confirm-loading="false"
      @cancel="printvisible = false"
      title="打印"
      :dialog-style="{ top: '20px' }"
    >
      <dingProcessView v-if="currentEnvironment == 'dingding'" :id="printId" :sortForm="sortForm" />
      <div v-if="currentEnvironment != 'dingding'">是否确定打印！</div>
      <template slot="footer">
        <a-button key="back" @click="printvisible = false"> 取消 </a-button>
        <a-button key="submit" type="primary">
          <circulationCard @changePrint="changePrint" :id="printId" :sortForm="sortForm" />
        </a-button>
      </template>
    </a-modal>
    <batch-production ref="BatchProduction"></batch-production>
    <windowDetail ref="windowDetail"></windowDetail>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, objArrFilter } from '@/utils/util'
import moment from 'dayjs'
import {
  getTaskOptionList,
  messProductBatchPageList,
  messProductBatchDel,
  messProductBatchPrint,
  getDictPageList,
} from '@/api/productOrder'
import { mapState } from 'vuex'
import tableDragResize from '@/mixins/tableDragResize'
import addModal from '@/views/workManagement/workOrder/printOutCard/addModal.vue'
import circulationCard from '@/views/workManagement/workOrder/print/circulationCard'
import dingProcessView from '@/views/workManagement/workOrder/print/dingProcessView'
import PubExport from '@/components/pubBtn/PubExport.vue'
import BatchProduction from '@/pubComponent/BatchProduction'
import PubImport from '@/components/pubBtn/PubImport.vue'
import windowDetail from '@/views/workManagement/workOrder/workOrderDetail'
// 表头
const columnsValue = [
  {
    title: '工单编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'orderCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'orderCode',
    },
  },
  {
    title: '批次编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'batchCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'batchCode',
    },
  },
  {
    title: '产品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'goodsCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsCode',
    },
  },
  {
    title: '产品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'goodsName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsName',
    },
  },
  {
    title: '规格',
    width: 120,
    ellipsis: true,
    dataIndex: 'goodsSpec',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsSpec',
    },
  },
  {
    title: '基本单位',
    width: 120,
    ellipsis: true,
    dataIndex: 'goodsBasicUnit',
    customRender: function (text, record) {
      return record.goodsBasicUnitText
    },
  },
  {
    title: '当前工序',
    width: 120,
    ellipsis: true,
    dataIndex: 'currentProcessId',
    selectKey: 'currentProcessId',
    list: 'currentProcessList',
    selectValue: 'id',
    selectText: 'processName',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'currentProcessId',
    },
    customRender: function (text, record) {
      return record.currentProcessName
    },
  },
  {
    title: '当前计划数',
    width: 100,
    ellipsis: true,
    dataIndex: 'currentPlanNum',
    customRender: function (text, record) {
      return record.currentPlanNumText
    },
  },
  {
    title: '初始工序',
    width: 120,
    ellipsis: true,
    dataIndex: 'originTaskId',
    selectKey: 'originProcessId',
    list: 'processList',
    selectValue: 'id',
    selectText: 'processName',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'originProcessName',
    },
    customRender: function (text, record) {
      return record.originProcessName
    },
  },
  {
    title: '计划生产数',
    width: 100,
    ellipsis: true,
    dataIndex: 'planProductionNum',
    customRender: function (text, record) {
      return record.planProductionNumText
    },
  },
  {
    title: '产量',
    width: 100,
    ellipsis: true,
    dataIndex: 'productNum',
    selectKey: 'productNum',
    list: 'productNumList',
    selectValue: 'value',
    selectText: 'text',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'productNum',
    },
    customRender: function (text, record) {
      return record.productNumText
    },
  },
  {
    title: '创建时间',
    width: 180,
    ellipsis: true,
    sorter: true,
    dataIndex: 'createTime',
    // scopedSlots: {
    //   filterDropdown: 'datePicker',
    //   filterIcon: 'selectIcon',
    //   customRender: 'createTime',
    // },
  },
  {
    title: '最后更新时间',
    width: 180,
    ellipsis: true,
    sorter: true,
    dataIndex: 'lastUpdateTime',
    // scopedSlots: {
    //   filterDropdown: 'datePicker',
    //   filterIcon: 'selectIcon',
    //   customRender: 'lastUpdateTime',
    // },
  },
  {
    title: '类型',
    width: 120,
    ellipsis: true,
    dataIndex: 'typeName',
    selectKey: 'type',
    list: 'typeList',
    selectValue: 'value',
    selectText: 'text',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'typeName',
    },
  },
  {
    title: '打印状态',
    width: 120,
    ellipsis: true,
    dataIndex: 'printStatusName',
    selectKey: 'printStatus',
    list: 'statusList',
    selectValue: 'value',
    selectText: 'text',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'printStatusName',
    },
  },
  {
    title: '打印次数',
    width: 120,
    ellipsis: true,
    sorter: true,
    dataIndex: 'printNum',
  },
]
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 120,
    dataIndex: 'actions',
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableDragResize],
  data() {
    return {
      moment,
      subStrText,
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      selectedRowKeys: [], // 列表已选择数据id
      selectedRows: [], // 列表已选择数据id
      showSetColumn: false, // 显示
      colunmArr: [
        {
          checkAll: false, //当前组是否全选
          indeterminate: false, //当前组不全选且有选择项时显示状态
          checkedList: [], //已选数据（不包括所有属性，只含有所选项的每一项的value）
          selectList: [], //已选数据（包括所有属性）
          topTitle: '基础字段', //当前组顶部字段
          plainOptions: [], //当前组提供可供选择的选项
        },
      ],
      //全选按钮
      indeterminate: false,
      checkAll: false,
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columns: [
        {
          title: '工单编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'orderCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'orderCode',
          },
        },
        {
          title: '批次编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'batchCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'batchCode',
          },
        },
        {
          title: '产品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '产品名称',
          width: 150,
          ellipsis: true,
          dataIndex: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsSpec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsSpec',
          },
        },
        {
          title: '基本单位',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsBasicUnit',
          customRender: function (text, record) {
            return record.goodsBasicUnitText
          },
        },
        {
          title: '当前工序',
          width: 120,
          ellipsis: true,
          dataIndex: 'currentProcessId',
          selectKey: 'currentProcessId',
          list: 'currentProcessList',
          selectValue: 'id',
          selectText: 'processName',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'currentProcessId',
          },
          customRender: function (text, record) {
            return record.currentProcessName
          },
        },
        {
          title: '当前计划数',
          width: 100,
          ellipsis: true,
          dataIndex: 'currentPlanNum',
          customRender: function (text, record) {
            return record.currentPlanNumText
          },
        },
        {
          title: '初始工序',
          width: 120,
          ellipsis: true,
          dataIndex: 'originTaskId',
          selectKey: 'originProcessId',
          list: 'processList',
          selectValue: 'id',
          selectText: 'processName',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'originProcessName',
          },
          customRender: function (text, record) {
            return record.originProcessName
          },
        },
        {
          title: '计划生产数',
          width: 100,
          ellipsis: true,
          dataIndex: 'planProductionNum',
          customRender: function (text, record) {
            return record.planProductionNumText
          },
        },
        {
          title: '产量',
          width: 100,
          ellipsis: true,
          dataIndex: 'productNum',
          customRender: function (text, record) {
            return record.productNumText
          },
          selectKey: 'productNum',
          list: 'productNumList',
          selectValue: 'value',
          selectText: 'text',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'productNum',
          },
        },
        {
          title: '创建时间',
          width: 180,
          ellipsis: true,
          sorter: true,
          dataIndex: 'createTime',
          // scopedSlots: {
          //   filterDropdown: 'datePicker',
          //   filterIcon: 'selectIcon',
          //   customRender: 'createTime',
          // },
        },
        {
          title: '最后更新时间',
          width: 180,
          ellipsis: true,
          sorter: true,
          dataIndex: 'lastUpdateTime',
          // scopedSlots: {
          //   filterDropdown: 'datePicker',
          //   filterIcon: 'selectIcon',
          //   customRender: 'lastUpdateTime',
          // },
        },
        {
          title: '类型',
          width: 120,
          ellipsis: true,
          dataIndex: 'typeName',
          selectKey: 'type',
          list: 'typeList',
          selectValue: 'value',
          selectText: 'text',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeName',
          },
        },
        {
          title: '打印状态',
          width: 120,
          ellipsis: true,
          dataIndex: 'printStatusName',
          selectKey: 'printStatus',
          list: 'statusList',
          selectValue: 'value',
          selectText: 'text',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'printStatusName',
          },
        },
        {
          title: '打印次数',
          width: 120,
          ellipsis: true,
          sorter: true,
          dataIndex: 'printNum',
        },
      ],
      dateForm: {},
      filterForm: {
        orderCode: '',
        batchCode: '',
        goodsCode: '',
        goodsName: '',
        goodsSpec: '',
        type: undefined,
        productNum: undefined,
        currentProcessId: undefined,
        originProcessId: undefined,
        printStatus: undefined,
        lastUpdateTimeBegin: null,
        createTimeBegin: null,
      },
      filteredFormLable: {
        orderCode: '工单编号',
        batchCode: '批次编号',
        goodsCode: '产品编号',
        goodsName: '产品名称',
        goodsSpec: '规格',
        type: '类型',
        productNum: '产量',
        currentProcessId: '当前工序',
        originProcessId: '初始工序',
        printStatus: '打印状态',
        lastUpdateTimeBegin: '最后更新时间',
        createTimeBegin: '创建时间',
      },
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      selectList: [],
      typeList: [
        { text: '添加', value: 'add' },
        { text: '系统', value: 'report' },
        { text: '返修', value: 'repair' },
      ],
      statusList: [
        { text: '已打印', value: 'printed' },
        { text: '未打印', value: 'not_printed' },
      ],
      productNumList: [
        { text: '为0', value: '0' },
        { text: '不为0', value: '1' },
      ],
      processList: [],
      currentProcessList: [],
      printId: '',
      printvisible: false,
      currentEnvironment: null,
      tableKey: 1.9,
      currentEnvironment: '',
      printvisible: false,
      // 导出begin
      exportUrl: '/mess/messProductBatch/exportPageListXls',
      chooseArr: [],
      allRequestList: [],
      fullName: `生产批次 ${moment(new Date()).format('YYYY-MM-DD HH:mm')}`,
      // 导出end
    }
  },
  components: {
    SetColumn,
    crumbs,
    addModal,
    circulationCard,
    dingProcessView,
    PubExport,
    BatchProduction,
    PubImport,
    windowDetail
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'originProcessId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          console.log(key);
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.processList.length; i++) {
            const e = this.processList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.id) {
                texts.push(e.processName)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'printStatus' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.statusList.length; i++) {
            const e = this.statusList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'type' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.typeList.length; i++) {
            const e = this.typeList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'currentProcessId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.currentProcessList.length; i++) {
            const e = this.currentProcessList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.id) {
                texts.push(e.processName)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'productNum' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.productNumList.length; i++) {
            const e = this.productNumList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'createTimeBegin' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: `${moment(this.filterForm['createTimeBegin']).format('YYYY-MM-DD')}~${moment(
              this.filterForm['createTimeEnd']
            ).format('YYYY-MM-DD')}`,
            key,
          })
        } else if (key == 'createTimeEnd' && this.filterForm[key]) {
        } else if (key == 'lastUpdateTimeBegin' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: `${moment(this.filterForm['lastUpdateTimeBegin']).format('YYYY-MM-DD')}~${moment(
              this.filterForm['lastUpdateTimeEnd']
            ).format('YYYY-MM-DD')}`,
            key,
          })
        } else if (key == 'lastUpdateTimeEnd' && this.filterForm[key]) {
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key] && this.filterForm[key].length > 0) {
          nums += 1
          if (key == 'lastUpdateTimeBegin' || key == 'createTimeBegin') {
            nums -= 1
          }
        }
      }
      return nums
    },
  },
  created() {
    this.initData()
    this.judgeEn()
    this.requestData()
  },
  methods: {
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    changeSelect(v, key) {
      if (v.length == 0) {
        this.filterForm[key] = undefined
      }
    },
    // 环境判断 浏览器/钉钉
    judgeEn() {
      this.currentEnvironment = sessionStorage.getItem('currentEnvironment')
      if (this.currentEnvironment) {
        if (this.timer) {
          clearInterval(this.timer)
          this.timer = null
        }
      } else {
        this.timer = setTimeout(() => {
          this.judgeEn()
        }, 100)
      }
    },
    // 打印后
    changePrint() {
      messProductBatchPrint(this.printId).then((res) => {
        if (res.success) {
          this.handleSearch()
        }
      })
      this.printvisible = false
    },
    getList(v) {
      return this[v] ? this[v] : []
    },
    // 设备二维码
    qrCode(v) {
      if (v) {
        this.printId = v.id
      } else {
        this.printId = this.selectedRowKeys.join(',')
      }
      this.printvisible = true
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)

          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
          this.selectedRows.push(item)

          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })

          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })

          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量删除
    batchAction() {
      let that = this
      if (that.selectedRows.length > 0) {
        let dtoList = []
        for (let i = 0; i < that.selectedRows.length; i++) {
          let item = that.selectedRows[i]
          if (item.type != 'add') {
            that.$antdMessage.warning('系统和返修类型的不能进行删除')
            return
          }
          if (item.realProductionNum) {
            that.$antdMessage.warning('该批次已流转无法进行删除操作')
            return
          }
          dtoList.push({
            id: item.id,
            orderId: item.orderId,
          })
        }
        console.log('next:', dtoList)
        that.$antdConfirm({
          title: '请确定要删除吗?',
          content: `共选中${that.selectedRowKeys.length}条信息`,
          onOk() {
            messProductBatchDel(dtoList).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('删除成功！')
                that.clearArr()
                that.handleSearch()
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    /* 清除 */
    clearArr() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.chooseArr = []
      this.checkBoxStatus()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (
        key == 'originProcessId' ||
        key == 'printStatus' ||
        key == 'type' ||
        key == 'currentProcessId' ||
        key == 'productNum'
      ) {
        this.filterForm[key] = undefined
      } else if (key == 'lastUpdateTimeBegin' || key == 'createTimeBegin') {
        this.filterForm[key] = ''
        this.dateForm[key] = null
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 时间选择 */
    onOk(value, key) {
      if (value.length == 0) {
        this.filterForm[`${key}Begin`] = ''
        this.filterForm[`${key}End`] = ''
        this.filterForm[key] = ''
        return
      }
      this.filterForm[`${key}Begin`] = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm[`${key}End`] = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        orderCode: '',
        createTimeBegin: null,
        lastUpdateTimeBegin: null,
        batchCode: '',
        goodsCode: '',
        goodsName: '',
        goodsSpec: '',
        currentProcessId: undefined,
        originProcessId: undefined,
        productNum: undefined,
        printStatus: undefined,
        type: undefined,
      }
      this.dateForm = {}
      this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.PRODUCTION_BATCH_LIST)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), actionArr, this.columns)
      // getTaskOptionList().then((res) => {
      //   this.processList = res.result || []
      // })
      getDictPageList({ pageSize: 999, pageNo: 1 }).then((res) => {
        this.currentProcessList = res.result.records || []
        this.processList = res.result.records || []
      })
    },
    /* 请求列表数据 */
    requestData(check) {
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.filterForm,
        ...this.sortForm,
      }
      for (let key in parameter) {
        if (!parameter[key]) {
          delete parameter[key]
        }
        if (parameter[key]) {
          if (
            key == 'originProcessId' ||
            key == 'printStatus' ||
            key == 'type' ||
            key == 'currentProcessId' ||
            key == 'productNum'
          ) {
            parameter[key] = parameter[key].join(',')
          }
        }
      }
      messProductBatchPageList(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          this.modelList = res.result.records
          this.allRequestList = this.allRequestList.concat(this.modelList)
          this.allRequestList = objArrFilter(this.allRequestList)
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(columnsValue, this.BUSI_CONST.Entity.PRODUCTION_BATCH_LIST, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, actionArr)
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.PRODUCTION_BATCH_LIST, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 导入 */
    importFile() {},
    /* 导出 */
    exportFile() {},
    /* 编辑 */
    handleEdit(v) {
      let obj = {
        batchCode: v.batchCode,
        id: v.id,
        orderId: v.orderId,
        originTaskId: v.originTaskId,
        processWorkUnitText: v.processWorkUnitText,
        planProductionNum: v.planProductionNum,
      }
      this.$refs.addModal.showEditModal(obj)
    },
    // 工单详情
    orderDetail(v) {
      let query = { id: v.orderId }
      this.$refs.windowDetail.initDetail(query)
    },
    // 批次详情
    batchDetail(v) {
      this.$refs.BatchProduction.showModal(v,'F')
    },
    /* 删除 */
    handleDelete(v) {
      let that = this
      that.$antdConfirm({
        title: '请确定要删除吗?',
        content: ``,
        onOk() {
          that.clearArr()
          messProductBatchDel([{ id: v.id, orderId: v.orderId }]).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('删除成功！')
              that.clearArr()
              if (that.modelList.length === 1) {
                that.current = that.current == 1 ? 1 : that.current - 1
              }
              that.requestData()
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    //点击返回按钮
    goBack() {
      this.$router.go(-1)
      console.log('goback')
    },
    /* 列表选择 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.chooseArr = []
      for (let tag of selectedRowKeys) {
        for (let item of this.allRequestList) {
          if (tag == item.id) {
            this.chooseArr.push(item)
          }
        }
      }
      this.checkBoxStatus()
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  margin-bottom: 10px;
  position: relative;
  padding: 0px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: 14px;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    margin: 8px 0;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 10px;
  }
}
.tag-wrap {
  margin-right: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.pagebox {
  /deep/ .ant-card-body {
    height: calc(100vh - 214px);
    overflow: hidden;
    padding: 20px 16px;
  }
}
</style>
